/**
 * 浏览页面顶部搜索框展开收回控制
 */
function toggleSearchFormShow() {
  let $ = layui.$
  let items = $('.top-search-from .layui-form-item')
  // TODO 2025 始终展开
  items.show()
  // if (items.length <= 2) {
  //   if (items.length <= 1) $('.top-search-from').parent().parent().remove()
  //   return
  // }
  // let btns = $('.top-search-from .toggle-btn a')
  // let toggle = toggleSearchFormShow
  // if (typeof toggle.hide === 'undefined') {
  //   btns.on('click', function () {
  //     toggle()
  //   })
  // }
  // let countPerRow = parseInt(
  //   $('.top-search-from').width() / $('.layui-form-item').width()
  // )
  // if (items.length <= countPerRow) {
  //   return
  // }
  // btns.removeClass('layui-hide')
  // toggle.hide = !toggle.hide
  // if (toggle.hide) {
  //   for (let i = countPerRow - 1; i < items.length - 1; i++) {
  //     $(items[i]).hide()
  //   }
  //   return $('.top-search-from .toggle-btn a:last').addClass('layui-hide')
  // }
  // items.show()
  // $('.top-search-from .toggle-btn a:first').addClass('layui-hide')
}

layui.$(function () {
  toggleSearchFormShow()
})

// Copy Text
function copyText(value) {
  let $ = layui.$
  let layer = layui.layer
  var $temp = $('<textarea>')
  $('body').append($temp)
  $temp.val(value).select()
  document.execCommand('copy')
  $temp.remove()
  layer.msg('已复制到剪贴板！')
}

// Download Text As File.
function downloadTextAsFile(text, filename, type = 'text/plain') {
  // 创建一个Blob对象
  const blob = new Blob([text], { type })

  // 创建一个下载链接
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename || 'download.txt'

  // 触发点击事件
  document.body.appendChild(a)
  a.click()

  // 清理
  setTimeout(() => {
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }, 0)
}

/**
 * 打开系统公告
 * @param {object} objs 公告消息
 */
function openNotify(objs = {}) {
  const { title = 'title', content = 'content', created_at = 'time' } = objs
  let layer = layui.layer
  layer.open({
    type: 1,
    title: '公告',
    shade: 0.1,
    area: [ isMobile() ? '96%' : '60%', '90%'],
    content: `
      <div class="notify-wrapper">
        <h1 style="text-align: center; line-height: 50px;">${title}</h1>
        <div style="text-align: right; color: #999; padding: 0 20px;">
          发布时间：${created_at}
        </div>
        <hr>
        <div style="padding: 0 40px; overflow: auto;">${content}</div>
      </div> 
    `,
  })
}

/**
 * 导出功能弹窗
 */
function openExportData(list = []) {
  if (!list || !list.length) return
  const layer = layui.layer
  const $ = layui.$
  function getExportType(callback) {
    $.ajax({
      url: '/app/admin/v1-api/getNodeExportTypeList',
      method: 'post',
      success(res) {
        if (res.code == 0) {
          const list = res.data || []
          callback(list)
        }
      },
    })
  }

  function formatExportData(formData) {
    // (IP|端口|账号|密码|到期)

    const { custom_line, format, format1, format_2 } = formData
    const symbol = custom_line || format_2
    const firtKey = format1 == 1 ? 'domain' : 'ip'

    if (format == 1) {
      // txt 格式
      const dataStr = list
        .map((item) =>
          [
            item[firtKey],
            item.port,
            item.account,
            item.pass,
            item.expire_time,
          ].join(symbol)
        )
        .join('\n')
      downloadTextAsFile(dataStr, '导出节点数据.txt')
    } else if (format == 2) {
      downloadTextAsFile(
        JSON.stringify(
          list.map((item) => ({
            [firtKey]: item[firtKey],
            port: item.port,
            account: item.account,
            pass: item.pass,
            expire_time: item.expire_time,
          }))
        ),
        '导出节点数据.json',
        'application/json'
      )
    }
  }

  layer.open({
    title: '导出定制',
    area: ['560px', '400px'],
    content: `
              <form class="layui-form layui-form-pane" lay-filter="export-form">
                <div class="layui-form-item" pane>
                  <label class="layui-form-label">返回格式</label>
                  <div class="layui-input-block">
                    <input type="radio" lay-filter="format" name="format" value="1" title="txt" checked />
                    <input type="radio" lay-filter="format" name="format" value="2" title="json" />
                  </div>
                </div>

                <div class="layui-form-item" pane>
                  <label class="layui-form-label">域名/IP</label>
                  <div class="layui-input-block">
                    <input type="radio" name="format1" value="2" title="IP" checked/>
                    <input type="radio" name="format1" value="1" title="域名" />
                  </div>
                </div>

                <div class="layui-form-item"
                  lay-filter="custom-linebreak"
                  pane
                  id="custom-linebreak_id"
                  >
                  <label class="layui-form-label">自定义行分隔符</label>
                  <div class="layui-input-block">
                    <input
                      type="text"
                      name="custom_line"
                      placeholder="请输入自定义行分隔符"
                      autocomplete="off"
                      class="layui-input"
                    />
                  </div>
                </div>

                <div class="layui-form-item"
                  pane
                  id="output_style_id"
                  >
                  <label class="layui-form-label">输出样式定制</label>
                  <div class="layui-input-block" id="output-style">
                  </div>
                </div>
              </form>
            `,

    btn: ['导出', '取消'],
    yes: function (index, layero) {
      formatExportData(layui.form.val('export-form'))
      setTimeout(() => layer.close(index), 600)
    },
    btn2: function (index, layero) {
      layer.close(index)
    },
    success: function (layero, index) {
      console.log(layero, index)
      getExportType((list) => {
        const fragment = new DocumentFragment()
        $.each(list, function (index, item) {
          // {id: 3, name: "格式3", content: "="}
          fragment.appendChild(
            $(`
            <input type="radio" name="format_2" value="${
              item.content
            }" title="${item.name}" ${index == 0 ? 'checked' : ''} data-id="${
              item.id
            }"/>
          `)[0]
          )
        })

        $('#output-style').html(fragment)

        layui.form.render(null, 'export-form')
      })
      layui.form.on('radio(format)', function (data) {
        const isJson = data.value == 2
        $('#custom-linebreak_id')[isJson ? 'hide' : 'show']()
        $('#output_style_id')[isJson ? 'hide' : 'show']()
      })
    },
  })
}

function isMobile() {
  return navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i) ? true : false
}
